package com.wogu.jwa.classes;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wogu.util.StringUtil;
import com.wogu.jwa.classes.AppConfig;

public class JwaServlet extends HttpServlet {
	private final static Properties config;
	private final static boolean isDebug;
	static {
		config = AppConfig.getConfig();
		isDebug = "true".equals(config.getProperty("debug"));
	}
	
	@SuppressWarnings("unchecked")
	private void _init(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		try {
			String charset = config.getProperty("charset");
			 //This method must be called prior to reading request parameters or reading input using getReader(). Otherwise, it has no effect.
			request.setCharacterEncoding(charset);
			//This method has no effect if it is called after getWriter has been called or after the response has been committed.
			response.setCharacterEncoding(charset);
		} catch(Exception e) {}
		
		ServletContext sc = getServletContext();
		String controller = route(request);
		Object obj = sc.getAttribute(controller);
		if(null == obj) {
			try {
				Class cls = Class.forName(controller);
				obj = cls.newInstance();
				sc.setAttribute(controller, obj);
			} catch(Exception e) {
				if(isDebug) e.printStackTrace(response.getWriter());
				else response.setStatus(HttpServletResponse.SC_NOT_FOUND);
			}
		}

		if(null != obj) {
			try {
				Method initMethod = obj.getClass().getMethod("init", HttpServletRequest.class, HttpServletResponse.class, HttpServlet.class);
				initMethod.invoke(obj, request, response, this);
			} catch(Exception e) {
				if(isDebug) e.printStackTrace(response.getWriter());
				else response.setStatus(HttpServletResponse.SC_NOT_FOUND);
			}
		}
	}
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		_init(request, response);
	}
	
	protected String getModuleName() {
		return null;
	}
	
	private String route(HttpServletRequest request) {
		String controller = request.getParameter("c");
		String module = request.getParameter("m");
		String moduleDefault = getModuleName();
		module = null == moduleDefault ? (null == module ? "default" : module) : moduleDefault;
		module = module.toLowerCase();
		String moduleBase = config.getProperty("module." + module + ".basepackage");
		moduleBase = null == moduleBase ? "com.wogu.jwa.web" : moduleBase;
		String modulePath = moduleBase + "." + module;
		controller = modulePath + "." + (null == controller ? "Default" : StringUtil.getClassName(controller));
		
		return controller;
	}
}